package com.skit.common.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.skit.common.http.NetResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

abstract class BaseViewModel : ViewModel() {
    fun <T> netResult(
        block: suspend () -> NetResult<T>,
        callBack: (NetResult<T>) -> Unit
    ): Job {
        return viewModelScope.launch {
            kotlin.runCatching {
                withContext(Dispatchers.IO) {
                    block()
                }
            }.onSuccess {
                callBack(it)
            }.onFailure {
                callBack(NetResult.Error(NetResult.Error.NET_ERROR, it.message))
            }
        }
    }
}